package com.doan.covua;


import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.doan.covua.gamelogic.ChessController;
import com.doan.covua.gamelogic.Move;
import com.doan.covua.gamelogic.MoveGen;
import com.doan.covua.gamelogic.Piece;
import com.doan.covua.gamelogic.Position;
import com.doan.covua.gamelogic.TextIO;


public class ChessActivity extends Activity implements OnClickListener, GUIInterface {

    // Debugging
    private static final String    TAG              = "ChessActivity";
    private static final boolean   D                = true;

    public static Position         pos;
    private static ChessController chessCtrl;
    private SoundManager           m_SoundManager;

    /* Define User Interface */
    private Dialog                 dialog;
    private Button                 m_ButtonYes;
    private Button                 m_ButtonNo;
    private LinearLayout           m_SplashScreen;
    private Button                 m_Help;
    private Button                 m_About;
    private Button                 m_AboutBack;
    private Button                 m_HelpBack;
    private Button                 m_HelpRules;
    private Button                 m_RulesBack;
    private Button                 m_Exit;
    private Button                 m_Options;
    private ImageButton            m_Board1;
    private ImageButton            m_Board2;
    private ImageButton            m_Board3;
    private ImageButton            m_Piece1;
    private ImageButton            m_Piece2;
    private ImageButton            m_Piece3;
    private CheckBox               m_SoundOn;
    private Button                 m_OptionsBack;
    private Button                 m_SinglePlayer;

    // Two player options
    private Button                 m_TwoPlayer;

    private ImageButton            m_PlayAsWhite;
    private ImageButton            m_PlayAsBlack;
    private ImageButton            m_PlayAsEasy;
    private ImageButton            m_PlayAsNormal;
    private ImageButton            m_PlayAsHard;
    private Button                 m_NewGameOptionsPlay;
    private Button                 m_NewGameOptionsBack;
    // In game define
    ChessBoard                     m_ChessBoard;
    TextView                       m_Name2;                                // m_Clock1,
                                                                            // m_Clock2;
    static ImageView               m_Check1;
    static ImageView               m_Check2;
    static ImageView               m_Thinking;
    // Button m_Undo;
    static AnimationDrawable       anim;
    static LinearLayout            m_Info1;
    static LinearLayout            m_Info2;
    static ImageView               m_Taken1[];
    static ImageView               m_Taken2[];

    /* Define general */
    public static boolean          s_isSfxOn;
    public static int              s_BoardSelected  = 2;
    public static int              s_PieceSelected  = 1;
    // default is white
    public static boolean          s_isPlayAsWhite  = true;
    // default is normal
    public static int              s_Difficulty     = 2;
    // single player
    public static boolean          s_isSinglePlayer = true;

    public static boolean          isBackToMainmenu = false;

    private int                    current_state    = 0;

    // piece index of m_Taken Array.
    private static int             pieceIndex1      = 0;
    private static int             pieceIndex2      = 0;

    private final int              EVENT_EXIT       = 0;
    private final int              EVENT_GOMAINMENU = EVENT_EXIT + 1;
    private final int              EVENT_NEWGAME    = EVENT_GOMAINMENU + 1;

    // Define for menu

    private final int              MENU_NEWGAME     = 0;
    private final int              MENU_OPTION      = 1;
    private final int              MENU_MAINMENU    = 2;
    private final int              MENU_HELP        = 3;
    private final int              MENU_EXIT        = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // init Sound
        initSound();

        Bundle receiveIsBackToMainmenu = this.getIntent().getExtras();
        if (receiveIsBackToMainmenu != null) {
            isBackToMainmenu = receiveIsBackToMainmenu.getBoolean("isBackToMainmenu", false);
            s_isSfxOn = receiveIsBackToMainmenu.getBoolean("isSound", false);
        }

        if (isBackToMainmenu) {
            isBackToMainmenu = false;
            setContentView(R.layout.mainmenu);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            findViewInMainMenu();
        } else {
            setContentView(R.layout.soundquestion);
            m_ButtonYes = (Button) findViewById(R.id.btn_yes);
            m_ButtonNo = (Button) findViewById(R.id.btn_no);
            m_ButtonYes.setOnClickListener(this);
            m_ButtonNo.setOnClickListener(this);
        }

    }

    /* Methods Define */
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_yes:
            s_isSfxOn = true;
            setContentView(R.layout.splashscreen);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            m_SplashScreen = (LinearLayout) findViewById(R.id.splashScreen);
            m_SplashScreen.setOnClickListener(this);
            break;
        case R.id.btn_no:
            s_isSfxOn = false;
            setContentView(R.layout.splashscreen);
            m_SplashScreen = (LinearLayout) findViewById(R.id.splashScreen);
            m_SplashScreen.setOnClickListener(this);
            break;
        case R.id.splashScreen:
            setContentView(R.layout.mainmenu);
            findViewInMainMenu();
            break;
        case R.id.btn_help:
            if (s_isSfxOn) {
                m_SoundManager.stopSoundTitle();
            }
            setContentView(R.layout.help);
            m_HelpBack = (Button) findViewById(R.id.help_back);
            m_HelpBack.setOnClickListener(this);
            m_HelpRules = (Button) findViewById(R.id.help_rules);
            m_HelpRules.setOnClickListener(this);
            break;
        case R.id.btn_about:
            setContentView(R.layout.about);
            if (s_isSfxOn) {
                m_SoundManager.stopSoundTitle();
            }
            m_AboutBack = (Button) findViewById(R.id.about_back);
            m_AboutBack.setOnClickListener(this);
            break;
        case R.id.help_back:
            setContentView(R.layout.mainmenu);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            findViewInMainMenu();
            break;
        case R.id.about_back:
            setContentView(R.layout.mainmenu);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            findViewInMainMenu();
            break;
        case R.id.help_rules:
            setContentView(R.layout.gamerules);
            m_RulesBack = (Button) findViewById(R.id.rules_back);
            m_RulesBack.setOnClickListener(this);
            break;
        case R.id.rules_back:
            setContentView(R.layout.mainmenu);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            findViewInMainMenu();
            break;
        case R.id.btn_exit:
            showCustomDialogYesno("Do you want to exit?", EVENT_EXIT);
            break;
        case R.id.btn_option:
            setContentView(R.layout.options);
            if (s_isSfxOn) {
                m_SoundManager.stopSoundTitle();
            }
            findViewInOptions();
            break;
        case R.id.Board1:
            ((ImageButton) v).setAlpha(255);
            m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            s_BoardSelected = 1;
            break;
        case R.id.Board2:
            ((ImageButton) v).setAlpha(255);
            m_Board1.setAlpha(128);
            m_Board3.setAlpha(128);
            s_BoardSelected = 2;
            break;
        case R.id.Board3:
            ((ImageButton) v).setAlpha(255);
            m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            s_BoardSelected = 3;
            break;
        case R.id.Piece1:
            ((ImageButton) v).setAlpha(255);
            m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            s_PieceSelected = 1;
            break;
        case R.id.Piece2:
            ((ImageButton) v).setAlpha(255);
            m_Piece1.setAlpha(128);
            m_Piece3.setAlpha(128);
            s_PieceSelected = 2;
            break;
        case R.id.Piece3:
            ((ImageButton) v).setAlpha(255);
            m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            s_PieceSelected = 3;
            break;
        case R.id.sound_selection:
            if (((CheckBox) v).isChecked()) {
                s_isSfxOn = true;
            } else {
                s_isSfxOn = false;
            }
            break;
        case R.id.options_back:
            setContentView(R.layout.mainmenu);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            findViewInMainMenu();
            break;
        case R.id.btn_single_player:
            s_isSinglePlayer = true;
            setContentView(R.layout.newgameoptions);
            if (s_isSfxOn) {
                m_SoundManager.stopSoundTitle();
            }
            findViewInSingleOptions();
            break;
        case R.id.btn_two_player:
            if (s_isSfxOn) {
                m_SoundManager.stopSoundTitle();
            }
            s_isSinglePlayer = false;
            Bundle sendInfo = new Bundle();
            sendInfo.putBoolean("isSound", s_isSfxOn);
            sendInfo.putInt("BoardSelected", s_BoardSelected);
            sendInfo.putInt("PieceSelected", s_PieceSelected);
            Intent menuIntent = new Intent(ChessActivity.this, Chess2PActivity.class);
            menuIntent.putExtras(sendInfo);
            startActivity(menuIntent);
            ChessActivity.this.finish();
            break;
        case R.id.newgameoptions_back:
            setContentView(R.layout.mainmenu);
            if (s_isSfxOn) {
                m_SoundManager.playSoundTitle();
            }
            findViewInMainMenu();
            break;
        case R.id.play_as_white:
            ((ImageButton) v).setAlpha(255);
            m_PlayAsBlack.setAlpha(128);
            s_isPlayAsWhite = true;
            break;
        case R.id.play_as_black:
            ((ImageButton) v).setAlpha(255);
            m_PlayAsWhite.setAlpha(128);
            s_isPlayAsWhite = false;
            break;
        case R.id.play_as_easy:
            ((ImageButton) v).setAlpha(255);
            m_PlayAsNormal.setAlpha(128);
            m_PlayAsHard.setAlpha(128);
            s_Difficulty = 1;
            break;
        case R.id.play_as_normal:
            ((ImageButton) v).setAlpha(255);
            m_PlayAsEasy.setAlpha(128);
            m_PlayAsHard.setAlpha(128);
            s_Difficulty = 2;
            break;
        case R.id.play_as_hard:
            ((ImageButton) v).setAlpha(255);
            m_PlayAsEasy.setAlpha(128);
            m_PlayAsNormal.setAlpha(128);
            s_Difficulty = 3;
            break;
        // in game play
        case R.id.newgameoptions_play:
            current_state = 1;
            // showDialog(PROGRESS_DIALOG);
            if (D) {
                Log.v("click on new option game play", "");
            }
            initUI();
            if (s_isPlayAsWhite) {
                chessCtrl = new ChessController(this, null);
                chessCtrl.newGame(new GameMode(GameMode.PLAYER_WHITE), true);
            } else {
                m_ChessBoard.setFlipped(true);
                chessCtrl = new ChessController(this, null);
                chessCtrl.newGame(new GameMode(GameMode.PLAYER_BLACK), true);
            }
            chessCtrl.startGame(s_isPlayAsWhite);
            updateBoardState();
            break;
        }

        // play sound select
        if (s_isSfxOn) {
            m_SoundManager.playSound(SoundManager.SOUND_SELECT);
        }
    }

    public void findViewInMainMenu() {
        m_SinglePlayer = (Button) findViewById(R.id.btn_single_player);
        m_SinglePlayer.setOnClickListener(this);
        m_TwoPlayer = (Button) findViewById(R.id.btn_two_player);
        m_TwoPlayer.setOnClickListener(this);
        m_Options = (Button) findViewById(R.id.btn_option);
        m_Options.setOnClickListener(this);
        m_Help = (Button) findViewById(R.id.btn_help);
        m_Help.setOnClickListener(this);
        m_About = (Button) findViewById(R.id.btn_about);
        m_About.setOnClickListener(this);
        m_Exit = (Button) findViewById(R.id.btn_exit);
        m_Exit.setOnClickListener(this);
    }

    public void findViewInOptions() {
        m_Board1 = (ImageButton) findViewById(R.id.Board1);
        m_Board2 = (ImageButton) findViewById(R.id.Board2);
        m_Board3 = (ImageButton) findViewById(R.id.Board3);
        m_Piece1 = (ImageButton) findViewById(R.id.Piece1);
        m_Piece2 = (ImageButton) findViewById(R.id.Piece2);
        m_Piece3 = (ImageButton) findViewById(R.id.Piece3);
        m_SoundOn = (CheckBox) findViewById(R.id.sound_selection);
        m_OptionsBack = (Button) findViewById(R.id.options_back);
        m_Board1.setOnClickListener(this);
        m_Board2.setOnClickListener(this);
        m_Board3.setOnClickListener(this);
        m_Piece1.setOnClickListener(this);
        m_Piece2.setOnClickListener(this);
        m_Piece3.setOnClickListener(this);
        m_SoundOn.setOnClickListener(this);
        m_OptionsBack.setOnClickListener(this);

        switch (s_BoardSelected) {
        case 1:
            // m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            break;
        case 2:
            m_Board1.setAlpha(128);
            // m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            break;
        case 3:
            m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            // m_Board3.setAlpha(128);
            break;
        }

        switch (s_PieceSelected) {
        case 1:
            // m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            break;
        case 2:
            m_Piece1.setAlpha(128);
            // m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            break;
        case 3:
            m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            // m_Piece3.setAlpha(128);
            break;
        }

        if (s_isSfxOn) {
            m_SoundOn.setChecked(true);
        }
    }

    public void findViewInSingleOptions() {
        m_PlayAsWhite = (ImageButton) findViewById(R.id.play_as_white);
        m_PlayAsBlack = (ImageButton) findViewById(R.id.play_as_black);
        m_PlayAsEasy = (ImageButton) findViewById(R.id.play_as_easy);
        m_PlayAsNormal = (ImageButton) findViewById(R.id.play_as_normal);
        m_PlayAsHard = (ImageButton) findViewById(R.id.play_as_hard);
        m_NewGameOptionsPlay = (Button) findViewById(R.id.newgameoptions_play);
        m_NewGameOptionsBack = (Button) findViewById(R.id.newgameoptions_back);
        m_PlayAsWhite.setOnClickListener(this);
        m_PlayAsBlack.setOnClickListener(this);
        m_PlayAsEasy.setOnClickListener(this);
        m_PlayAsNormal.setOnClickListener(this);
        m_PlayAsHard.setOnClickListener(this);
        m_NewGameOptionsPlay.setOnClickListener(this);
        m_NewGameOptionsBack.setOnClickListener(this);

        if (s_isPlayAsWhite) {
            m_PlayAsBlack.setAlpha(128);
        } else {
            m_PlayAsWhite.setAlpha(128);
        }
        switch (s_Difficulty) {
        case 1:
            // m_PlayAsEasy.setAlpha(128);
            m_PlayAsNormal.setAlpha(128);
            m_PlayAsHard.setAlpha(128);
            break;
        case 2:
            m_PlayAsEasy.setAlpha(128);
            // m_PlayAsNormal.setAlpha(128);
            m_PlayAsHard.setAlpha(128);
            break;
        case 3:
            m_PlayAsEasy.setAlpha(128);
            m_PlayAsNormal.setAlpha(128);
            // m_PlayAsHard.setAlpha(128);
        }
    }

    public void findViewInTwoPlayerOption() {
    }

    public void initUI() {
        setContentView(R.layout.ingame_singlemode);
        m_ChessBoard = (ChessBoard) findViewById(R.id.chess);
        m_Name2 = (TextView) findViewById(R.id.Name2);
        // m_Clock1 = (TextView) findViewById(R.id.Clock1);
        // m_Clock2 = (TextView) findViewById(R.id.Clock2);
        m_Check1 = (ImageView) findViewById(R.id.isCheck1);
        m_Check2 = (ImageView) findViewById(R.id.isCheck2);
        m_Thinking = (ImageView) findViewById(R.id.isThinking);
        // m_Undo = (Button) findViewById(R.id.ButtonUndo);

        m_Info1 = (LinearLayout) findViewById(R.id.Info1);
        m_Info2 = (LinearLayout) findViewById(R.id.Info2);
        findViewTaken();

        m_ChessBoard.setFocusable(true);
        m_ChessBoard.requestFocus();
        m_ChessBoard.setClickable(true);
        m_Name2.setFocusable(false);
        // m_Clock1.setFocusable(false);
        // m_Clock2.setFocusable(false);
        m_Check1.setFocusable(false);
        m_Check2.setFocusable(false);
        m_Thinking.setFocusable(false);

        m_ChessBoard.setOnClickListener(this);
        // m_Undo.setOnClickListener(this);

        m_Thinking.setImageResource(R.drawable.src_thinking_anim);
        m_Thinking.setVisibility(View.INVISIBLE);

        anim = (AnimationDrawable) m_Thinking.getDrawable();

        final GestureDetector gd = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
            private float scrollX = 0;
            private float scrollY = 0;

            @Override
            public boolean onDown(MotionEvent e) {
                scrollX = 0;
                scrollY = 0;
                return false;
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                m_ChessBoard.cancelLongPress();
                handleClick(e);
                return true;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                if (e.getAction() == MotionEvent.ACTION_UP) {
                    handleClick(e);
                }
                return true;
            }

            private final void handleClick(MotionEvent e) {
                if (chessCtrl.humansTurn()) {
                    if (D) {
                        Log.v(TAG, "handle click");
                    }
                    int sq = m_ChessBoard.eventToSquare(e);
                    Move m = m_ChessBoard.mousePressed(sq);
                    if (m != null) {
                        if (D) {
                            Log.v(TAG, "Make move when m != null");
                        }
                        // get current pos befor move
                        Position pos2 = new Position(chessCtrl.currPos());
                        chessCtrl.makeHumanMove(m);
                        if (chessCtrl.getDoMove()) {
                            // draw last move
                            ChessBoard.setLastMove(m, true);
                            updateCheckStatus(chessCtrl.currPos());
                            startThinkingAnim();
                            drawCapturedPiece(pos2, m);
                        }
                        updateBoardState();
                    } else {
                        m_ChessBoard.setLegalMoveofSquare(chessCtrl.legalMoveOfSquare(sq));
                    }
                }
            }
        });
        m_ChessBoard.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                return gd.onTouchEvent(event);
            }
        });
    }

    public void showCustomDialog(int dialogId) {
        dialog = new Dialog(ChessActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(dialogId);
        dialog.setCancelable(false);
        dialog.show();
    }

    public void setPosition(Position pos, String variantInfo, List<Move> variantMoves) {
        m_ChessBoard.setPosition(pos);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ChessBoard oldCB = m_ChessBoard;
        initUI();
        m_ChessBoard.setPosition(oldCB.pos);
        m_ChessBoard.cursorX = oldCB.cursorX;
        m_ChessBoard.cursorY = oldCB.cursorY;
        m_ChessBoard.oneTouchMoves = oldCB.oneTouchMoves;
        setSelection(oldCB.selectedSquare);
    }

    public void setSelection(int sq) {
        m_ChessBoard.setSelection(sq);
    }

    /** Report a move made that is a candidate for GUI animation. */
    public void setAnimMove(Position sourcePos, Move move, boolean forward) {
        if (/* animateMoves && */(move != null)) {
            m_ChessBoard.setAnimMove(sourcePos, move, forward);
        }
    }

    public void initSound() {
        m_SoundManager = new SoundManager();
        m_SoundManager.initSounds(getBaseContext());
        m_SoundManager.addSound(SoundManager.SOUND_SELECT, R.raw.select);
        m_SoundManager.addSound(SoundManager.SOUND_CHECK, R.raw.voicecheckmate);
        m_SoundManager.addSound(SoundManager.SOUND_PICEDROP, R.raw.piecedrop);
    }

    /*
     * phuong update
     */
    public void runOnUIThread(Runnable runnable) {
        runOnUiThread(runnable);
    }

    private static String    gameState       = "";
    static final int         PROGRESS_DIALOG = 0;
    private static final int RESULTGAME      = 1;
    private static final int PROMOTE_DIALOG  = 2;

    ProgressThread           progressThread;
    ProgressDialog           progressDialog;

    public void setStatusString(String str) {
        gameState = str;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {

        case PROGRESS_DIALOG:
            Log.v("progress......", "");
            progressDialog = new ProgressDialog(ChessActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setMessage("Loading...");
            return progressDialog;

        case RESULTGAME:

            final Dialog dialog = new Dialog(this);

            dialog.setContentView(R.layout.game_result);
            dialog.setTitle("RESULT");

            TextView text = (TextView) dialog.findViewById(R.id.game_result_text);
            text.setText(gameState);
            return dialog;

        case PROMOTE_DIALOG:
            final CharSequence[] items = { getString(R.string.queen), getString(R.string.rook), getString(R.string.bishop),
                    getString(R.string.knight) };
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.promote_pawn_to);
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    // TODO Auto-generated method stub
                    chessCtrl.reportPromotePiece(item);
                }
            });
            AlertDialog alert = builder.create();
            return alert;

        }
        return null;
    }

    public void showGameResult() {

        // showDialog(RESULTGAME);
        showCustomDialogOk(gameState);
    }

    public void requestPromotePiece() {
        runOnUIThread(new Runnable() {
            public void run() {
                showDialog(PROMOTE_DIALOG);
            }
        });
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case PROGRESS_DIALOG:
            progressDialog.setProgress(0);
            progressThread = new ProgressThread(handler);
            progressThread.start();
        }
    }

    // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
                              @Override
                              public void handleMessage(Message msg) {
                                  int total = msg.arg1;
                                  progressDialog.setProgress(total);
                                  if (total >= 100) {
                                      dismissDialog(PROGRESS_DIALOG);
                                      progressThread.setState(ProgressThread.STATE_DONE);
                                  }
                              }
                          };

    /** Nested class that performs progress calculations (counting) */
    private class ProgressThread extends Thread {
        Handler          mHandler;
        final static int STATE_DONE    = 0;
        final static int STATE_RUNNING = 1;
        int              mState;
        int              total;

        ProgressThread(Handler h) {
            mHandler = h;
        }

        @Override
        public void run() {
            mState = STATE_RUNNING;
            total = 0;
            while (mState == STATE_RUNNING) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Log.e("ERROR", "Thread Interrupted");
                }
                Message msg = mHandler.obtainMessage();
                msg.arg1 = total;
                mHandler.sendMessage(msg);
                total++;
            }
        }

        /*
         * sets the current state for the thread, used to stop the thread
         */
        public void setState(int state) {
            mState = state;
        }

    }

    // show custom dialog exit
    private void showCustomDialogYesno(String text, final int event) {
        dialog = new Dialog(ChessActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.dialog_yesno);
        dialog.setCancelable(false);
        dialog.show();
        TextView tv = (TextView) dialog.findViewById(R.id.dialog_yesno_text);
        tv.setText(text);
        Button btyes = (Button) dialog.findViewById(R.id.dialog_yes_button);
        btyes.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                switch (event) {
                case EVENT_EXIT:
                    m_SoundManager.stopSoundTitle();
                    ChessActivity.this.finish();
                    break;
                case EVENT_GOMAINMENU:
                    current_state = 0;
                    dialog.dismiss();
                    goToMainMenu();
                    break;
                case EVENT_NEWGAME:
                    // reset capture piece
                    for (int i = 0; i < pieceIndex1; i++) {
                        m_Taken1[i].setImageResource(0);
                    }
                    for (int i = 0; i < pieceIndex2; i++) {
                        m_Taken2[i].setImageResource(0);
                    }
                    pieceIndex1 = 0;
                    pieceIndex2 = 0;
                    updateBoardState();
                    updateCheckStatus(chessCtrl.currPos());
                    newGame();
                    dialog.dismiss();
                    break;
                }
            }
        });
        Button btno = (Button) dialog.findViewById(R.id.dialog_no_button);
        btno.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    // init menu
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if (current_state == 1) {
            // menu.add(0, MENU_RECONNECT, 0, "Reconnect").setIcon(R.drawable.ic_menu_reconnect);
            menu.add(0, MENU_NEWGAME, 0, "New game").setIcon(R.drawable.ic_menu_newgame);
            menu.add(0, MENU_OPTION, 0, "Options").setIcon(R.drawable.ic_menu_option);
            menu.add(0, MENU_MAINMENU, 0, "Main menu").setIcon(R.drawable.ic_menu_mainmenu);
            menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help);
            menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    // manage select menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_NEWGAME:
            showCustomDialogYesno("Are you sure?", EVENT_NEWGAME);
            return true;
        case MENU_OPTION:
            showCustomDialogOptions();
            return true;
        case MENU_MAINMENU:
            showCustomDialogYesno("Are you sure?", EVENT_GOMAINMENU);
            return true;
        case MENU_HELP:
            showCustomDialogHelp();
            return true;
        case MENU_EXIT:
            showCustomDialogYesno("Do you want to exit?", EVENT_EXIT);
            return true;
        }
        return false;
    }

    // show dialog options
    private void showCustomDialogOptions() {
        dialog = new Dialog(ChessActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.options);
        dialog.setCancelable(false);
        dialog.show();
        final ImageButton m_Board1 = (ImageButton) dialog.findViewById(R.id.Board1);
        final ImageButton m_Board2 = (ImageButton) dialog.findViewById(R.id.Board2);
        final ImageButton m_Board3 = (ImageButton) dialog.findViewById(R.id.Board3);
        final ImageButton m_Piece1 = (ImageButton) dialog.findViewById(R.id.Piece1);
        final ImageButton m_Piece2 = (ImageButton) dialog.findViewById(R.id.Piece2);
        final ImageButton m_Piece3 = (ImageButton) dialog.findViewById(R.id.Piece3);
        final CheckBox m_SoundOn = (CheckBox) dialog.findViewById(R.id.sound_selection);
        Button m_OptionsBack = (Button) dialog.findViewById(R.id.options_back);
        m_Board1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Board1.setAlpha(255);
                m_Board2.setAlpha(128);
                m_Board3.setAlpha(128);
                s_BoardSelected = 1;
            }
        });
        m_Board2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Board2.setAlpha(255);
                m_Board1.setAlpha(128);
                m_Board3.setAlpha(128);
                s_BoardSelected = 2;
            }
        });
        m_Board3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Board3.setAlpha(255);
                m_Board1.setAlpha(128);
                m_Board2.setAlpha(128);
                s_BoardSelected = 3;
            }
        });
        m_Piece1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Piece1.setAlpha(255);
                m_Piece2.setAlpha(128);
                m_Piece3.setAlpha(128);
                s_PieceSelected = 1;
            }
        });
        m_Piece2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Piece2.setAlpha(255);
                m_Piece1.setAlpha(128);
                m_Piece3.setAlpha(128);
                s_PieceSelected = 2;
            }
        });
        m_Piece3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Piece3.setAlpha(255);
                m_Piece1.setAlpha(128);
                m_Piece2.setAlpha(128);
                s_PieceSelected = 3;
            }
        });
        m_SoundOn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (m_SoundOn.isChecked()) {
                    s_isSfxOn = true;
                } else {
                    s_isSfxOn = false;
                }
            }
        });
        m_OptionsBack.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
                m_ChessBoard.setBoardAndPiece(s_BoardSelected, s_PieceSelected);
            }
        });

        switch (s_BoardSelected) {
        case 1:
            // m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            break;
        case 2:
            m_Board1.setAlpha(128);
            // m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            break;
        case 3:
            m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            // m_Board3.setAlpha(128);
            break;
        }

        switch (s_PieceSelected) {
        case 1:
            // m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            break;
        case 2:
            m_Piece1.setAlpha(128);
            // m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            break;
        case 3:
            m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            // m_Piece3.setAlpha(128);
            break;
        }

        if (s_isSfxOn) {
            m_SoundOn.setChecked(true);
        }

    }

    // show dialog help
    private void showCustomDialogHelp() {
        dialog = new Dialog(ChessActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.help);
        dialog.setCancelable(false);
        dialog.show();
        Button btnBack = (Button) dialog.findViewById(R.id.help_back);
        btnBack.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Button btnRules = (Button) dialog.findViewById(R.id.help_rules);
        btnRules.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.setContentView(R.layout.gamerules);
                Button btnRulesBack = (Button) dialog.findViewById(R.id.rules_back);
                btnRulesBack.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    // Go to main menu
    private void goToMainMenu() {
        s_BoardSelected = 2;
        s_PieceSelected = 1;
        s_isPlayAsWhite = true;
        pieceIndex1 = 0;
        pieceIndex2 = 0;
        Bundle isBackToMainmenu = new Bundle();
        isBackToMainmenu.putBoolean("isBackToMainmenu", true);
        isBackToMainmenu.putBoolean("isSound", s_isSfxOn);
        // Intent menuIntent = new Intent(ChessActivity.this, ChessActivity.class);
        // menuIntent.putExtras(isBackToMainmenu);
        // startActivity(menuIntent);
        // ChessActivity.this.finish();
        Intent intent = ChessActivity.this.getIntent();
        intent.putExtras(isBackToMainmenu);
        ChessActivity.this.finish();
        startActivity(intent);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (D) {
                Log.v(TAG, "BACK button is pressed!");
            }
        }
        return false;
    }

    // start anim thinking
    public void startThinkingAnim() {
        if (m_Thinking != null) {
            m_Thinking.setVisibility(View.VISIBLE);
            if (anim != null) {
                anim.stop();
                anim.start();
            }
        }
    }

    // stop anim thinking
    public static void stopThinkingAnim() {
        if (m_Thinking != null) {
            if (anim != null) {
                anim.stop();
                m_Thinking.setVisibility(View.INVISIBLE);
            }
        }
    }

    // check and draw CHECK status
    public static void updateCheckStatus(Position pos) {
        if (MoveGen.inCheck(pos)) {
            if (chessCtrl.currPos().whiteMove ^ s_isPlayAsWhite) {
                m_Check2.setVisibility(View.VISIBLE);
            } else {
                m_Check1.setVisibility(View.VISIBLE);
            }
        } else {
            m_Check1.setVisibility(View.INVISIBLE);
            m_Check2.setVisibility(View.INVISIBLE);
        }
    }

    // show custom dialog ok
    private void showCustomDialogOk(String text) {
        final Dialog dialog2 = new Dialog(ChessActivity.this, R.style.PlaqueTheme);
        dialog2.setContentView(R.layout.dialog_ok);
        dialog2.setCancelable(false);
        dialog2.show();
        TextView tv = (TextView) dialog2.findViewById(R.id.dialog_ok_text);
        tv.setText(text);
        Button bt = (Button) dialog2.findViewById(R.id.dialog_ok_button);
        bt.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog2.dismiss();
            }
        });
    }

    public static void updateBoardState() {
        // update UI state bar of myturn
        if (m_Info1 != null && m_Info2 != null) {
            if (chessCtrl.currPos().whiteMove ^ s_isPlayAsWhite) {
                m_Info2.setBackgroundDrawable(null);
                m_Info1.setBackgroundResource(R.drawable.player_info_overlay);
            } else {
                m_Info1.setBackgroundDrawable(null);
                m_Info2.setBackgroundResource(R.drawable.player_info_overlay);
            }
        }
    }

    private void findViewTaken() {
        m_Taken1 = new ImageView[16];
        m_Taken1[0] = (ImageView) findViewById(R.id.Taken1_1);
        m_Taken1[1] = (ImageView) findViewById(R.id.Taken1_2);
        m_Taken1[2] = (ImageView) findViewById(R.id.Taken1_3);
        m_Taken1[3] = (ImageView) findViewById(R.id.Taken1_4);
        m_Taken1[4] = (ImageView) findViewById(R.id.Taken1_5);
        m_Taken1[5] = (ImageView) findViewById(R.id.Taken1_6);
        m_Taken1[6] = (ImageView) findViewById(R.id.Taken1_7);
        m_Taken1[7] = (ImageView) findViewById(R.id.Taken1_8);
        m_Taken1[8] = (ImageView) findViewById(R.id.Taken1_9);
        m_Taken1[9] = (ImageView) findViewById(R.id.Taken1_10);
        m_Taken1[10] = (ImageView) findViewById(R.id.Taken1_11);
        m_Taken1[11] = (ImageView) findViewById(R.id.Taken1_12);
        m_Taken1[12] = (ImageView) findViewById(R.id.Taken1_13);
        m_Taken1[13] = (ImageView) findViewById(R.id.Taken1_14);
        m_Taken1[14] = (ImageView) findViewById(R.id.Taken1_15);
        m_Taken1[15] = (ImageView) findViewById(R.id.Taken1_16);

        m_Taken2 = new ImageView[16];
        m_Taken2[0] = (ImageView) findViewById(R.id.Taken2_1);
        m_Taken2[1] = (ImageView) findViewById(R.id.Taken2_2);
        m_Taken2[2] = (ImageView) findViewById(R.id.Taken2_3);
        m_Taken2[3] = (ImageView) findViewById(R.id.Taken2_4);
        m_Taken2[4] = (ImageView) findViewById(R.id.Taken2_5);
        m_Taken2[5] = (ImageView) findViewById(R.id.Taken2_6);
        m_Taken2[6] = (ImageView) findViewById(R.id.Taken2_7);
        m_Taken2[7] = (ImageView) findViewById(R.id.Taken2_8);
        m_Taken2[8] = (ImageView) findViewById(R.id.Taken2_9);
        m_Taken2[9] = (ImageView) findViewById(R.id.Taken2_10);
        m_Taken2[10] = (ImageView) findViewById(R.id.Taken2_11);
        m_Taken2[11] = (ImageView) findViewById(R.id.Taken2_12);
        m_Taken2[12] = (ImageView) findViewById(R.id.Taken2_13);
        m_Taken2[13] = (ImageView) findViewById(R.id.Taken2_14);
        m_Taken2[14] = (ImageView) findViewById(R.id.Taken2_15);
        m_Taken2[15] = (ImageView) findViewById(R.id.Taken2_16);
    }

    // draw capture piece
    public static void drawCapturedPiece(Position pos, Move m) {
        if (TextIO.isCapture(pos, m)) {
            int piece = pos.getPiece(m.to);
            switch (s_PieceSelected) {
            case 1:
                if (s_isPlayAsWhite ^ Piece.isWhite(piece)) {
                    m_Taken1[pieceIndex1++].setImageResource(Chess2PActivity.pieceImage1[piece]);
                } else {
                    m_Taken2[pieceIndex2++].setImageResource(Chess2PActivity.pieceImage1[piece]);
                }
                break;
            case 2:
                if (s_isPlayAsWhite ^ Piece.isWhite(piece)) {
                    m_Taken1[pieceIndex1++].setImageResource(Chess2PActivity.pieceImage2[piece]);
                } else {
                    m_Taken2[pieceIndex2++].setImageResource(Chess2PActivity.pieceImage2[piece]);
                }
                break;
            case 3:
                if (s_isPlayAsWhite ^ Piece.isWhite(piece)) {
                    m_Taken1[pieceIndex1++].setImageResource(Chess2PActivity.pieceImage3[piece]);
                } else {
                    m_Taken2[pieceIndex2++].setImageResource(Chess2PActivity.pieceImage3[piece]);
                }
                break;
            }
        }
    }

    // end draw

    private void newGame() {
        if (s_isPlayAsWhite) {
            // chessCtrl = new ChessController(this, null);
            chessCtrl.newGame(new GameMode(GameMode.PLAYER_WHITE), true);
        } else {
            m_ChessBoard.setFlipped(true);
            // chessCtrl = new ChessController(this, null);
            chessCtrl.newGame(new GameMode(GameMode.PLAYER_BLACK), true);
        }
        chessCtrl.startGame(s_isPlayAsWhite);
        updateBoardState();
    }
}
